package com.yixun.qfbao.filters;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yixun.qfbao.hander.BatchAddPremisesRecommenderHander;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.Resources;
import com.yixun.qfbao.model.dto.UserResourcesDto;
import com.yixun.qfbao.service.SysReourceService;
import com.yixun.qfbao.utils.WebUtil;

/**
 * 资源权限 1.报备列表
 */
@WebFilter(urlPatterns = {"/developers/reportPreparationResponese", "/developers/crateFollow", "/developers/customerToM2", "/developers/exportInfo",
	"/developers/reportChangeStatus", "/developers/confirmStatusEdit", "/developers/reportChangeStatus",
	"/department/checkCooDept"}, filterName = "resourceFilter")
public class ResourceFilter implements Filter {
	private static Logger logger= LoggerFactory.getLogger(ResourceFilter.class);
	
	@Autowired
	SysReourceService sysReourceService;
	
	@Override
	public void init(FilterConfig filterConfig)
		throws ServletException {
		
	}
	
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
		throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		HttpServletResponse response = (HttpServletResponse)servletResponse;
		PartnerInfo info = WebUtil.getPartnerInfo(request);
		if ("0".equals(info.getAccountType())) {// 管理员直接跳过
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		} else {
			if (info.getUserRoleId() == null) {// 非管理员，没有分配角色
				sendErrorMessage(request, response);
				return;
			}
		}
		
		UserResourcesDto userResourcesDto = new UserResourcesDto();
		// 不是管理员
		if (info.getAccountType().equals("1")) {
			userResourcesDto.setUserId(info.getId());
		}
		// 获取 资源权限
		List<Resources> list = sysReourceService.getReourcesByRole(userResourcesDto);
		// 判断权限
		String uri = request.getServletPath();
		boolean flag = false;
		for (Resources r : list) {
			if (uri.equals(r.getResourcesHref())) {
				flag = true;
				break;
			}
		}
		if (flag) {
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		} else {// 无权限 返回前台信息
			if (WebUtil.isAjax(request)) {
				sendErrorMessage(request, response);
			} else {
				// 导出是新打开的页面
				if (uri.contains("exportInfo")) {
					response.setContentType("text/html;charset=utf-8");
					response.getOutputStream().write(("<script language='javascript'> alert('无导出权限');window.location.href='"
						+ request.getContextPath() + "/developers/customerManagement';</script>").getBytes("utf-8"));
				}
			}
			
			return;
		}
		
	}
	
	@Override
	public void destroy() {
	
	}
	
	private void sendErrorMessage(HttpServletRequest request, HttpServletResponse response) {
		ServletOutputStream out = null;
		try {
			if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {// ajax请求
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/json; charset=utf-8");
				out = response.getOutputStream();
				out.write(("{\"result\":\"-1\",\"errorMsg\":\"没有相应权限！\"}").getBytes("UTF-8"));
			}
		} catch (IOException e) {
			logger.error("sendErrorMessage error: {}", e);
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					logger.error("ServletOutputStream error: {}", e);
				}
			}
		}
	}
}
